package com.sanerzone.smscenter.gateway.http;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.RateLimiter;
import com.sanerzone.common.support.storedMap.BDBStoredMapFactoryImpl;
import com.sanerzone.common.support.utils.Encodes;
import com.sanerzone.smscenter.biz.cache.GatewayCacheHelper;
import com.sanerzone.smscenter.biz.entity.SmsGateway;
import com.sanerzone.smscenter.biz.listener.UmsMOListener;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSSRMessage;
import com.sanerzone.smscenter.biz.utils.StringHelper;
import com.sanerzone.smscenter.gateway.base.BaseGatewayFactory;
import com.sanerzone.smscenter.gateway.base.GateEnum;
import com.sanerzone.smscenter.gateway.base.GateStateEnum;
import com.sanerzone.smscenter.gateway.base.Result;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.service.ISmsGatewayService;
import com.sanerzone.smscenter.gateway.ums.comm.cmpp.CMPPSMProxy;
import com.sanerzone.smscenter.gateway.ums.comm.cmpp.message.CMPPSubmitMessage;
import com.sanerzone.smscenter.gateway.ums.comm.cmpp.message.CMPPSubmitRepMessage;
import com.sanerzone.smscenter.gateway.ums.comm.cmpp3.CMPP30SMProxy;
import com.sanerzone.smscenter.gateway.ums.comm.sgip.SGIPSMProxy;
import com.sanerzone.smscenter.gateway.ums.comm.sgip.message.SGIPSubmitMessage;
import com.sanerzone.smscenter.gateway.ums.comm.sgip.message.SGIPSubmitRepMessage;
import com.sanerzone.smscenter.gateway.ums.comm.smgp.SMGPSMProxy;
import com.sanerzone.smscenter.gateway.ums.comm.smgp.message.SMGPSubmitMessage;
import com.sanerzone.smscenter.gateway.ums.comm.smgp.message.SMGPSubmitRespMessage;
import com.sanerzone.smscenter.gateway.ums.comm.smgp3.SMGP3SMProxy;
import com.sanerzone.smscenter.gateway.ums.comm.smgp3.message.SMGP3SubmitMessage;
import com.sanerzone.smscenter.gateway.ums.comm.smgp3.message.SMGP3SubmitRespMessage;
import com.sanerzone.smscenter.gateway.ums.message.factory.CMPPMsgFactory;
import com.sanerzone.smscenter.gateway.ums.message.factory.SGIPMsgFactory;
import com.sanerzone.smscenter.gateway.ums.message.factory.SMGP3MsgFactory;
import com.sanerzone.smscenter.gateway.ums.message.factory.SMGPMsgFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * <一句话功能简述>
 * <功能详细描述>
 *
 * @author zhangjie
 * @version [版本号, 2016年8月27日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class HttpGatewayFactory extends BaseGatewayFactory {
    private static final Logger logger = LoggerFactory.getLogger(HttpGatewayFactory.class);

    //网关
    public static Map<String, GateWayHttpAbstract> GATEWAY_MAP = Maps.newConcurrentMap();
    //ums proxy
    private static final Map<String, Object> GATEWAY_TYPE = new HashMap<String, Object>();

    private static SGIPMsgFactory sgipMsgFactory = new SGIPMsgFactory();
    private CMPPMsgFactory cmppMsgFactory = new CMPPMsgFactory();
    private SMGP3MsgFactory smgp3MsgFactory = new SMGP3MsgFactory();
    private SMGPMsgFactory smgpMsgFactory = new SMGPMsgFactory();
    private static UmsMOListener moListener = new UmsMOListener();
    @Autowired
    private ISmsGatewayService smsGatewayService;

    private int fmt_cmpp = 8;
    private int fmt_cmpp30 = 8;
    private int fmt_sgip = 8;
    private int fmt_smgp = 8;
    private int fmt_smgp3 = 8;

    private static Map<String, Serializable> storedMap = getStoredMap();

    public static Map<String, Serializable> getStoredMap() {
        if (storedMap == null) {
            storedMap = BDBStoredMapFactoryImpl.INS.buildMap("ums", "message");
        }
        return storedMap;
    }

    public ISmsGatewayService getSmsGatewayService() {
        return smsGatewayService;
    }

    public void setSmsGatewayService(ISmsGatewayService smsGatewayService) {
        this.smsGatewayService = smsGatewayService;
    }

    @Override
    public void initGateway(String appCode) {
        SmsGateway smsGateway = new SmsGateway();
        smsGateway.setAppCode(appCode);
        List<SmsGateway> list = smsGatewayService.findList(smsGateway);
        for (SmsGateway tmp : list) {
            boolean res = false;
            try {
                res = initGate(tmp);
                if (res) {
                    tmp.setGwStatus(GateStateEnum.ENABLED.getValue());
                    smsGatewayService.updateStatus(tmp);
                } else {
                    tmp.setGwStatus(GateStateEnum.ERROR.getValue());
                    smsGatewayService.updateStatus(tmp);
                }
            } catch (Exception e) {
                tmp.setGwStatus(GateStateEnum.ERROR.getValue());
                smsGatewayService.updateStatus(tmp);
                logger.error("初始化网关失败", e);
            }
            if (res) {
                if (logger.isInfoEnabled()) {
                    logger.info("初始化网关成功:[" + tmp + "]");
                }
            } else {
                if (logger.isInfoEnabled()) {
                    logger.info("初始化网关失败:[" + tmp + "]");
                }
            }
        }
    }

    private synchronized boolean initGate(SmsGateway gateway) {
         /*gateway = new JmsgGateWayInfo();
         gateway.setId("DX5005");
         gateway.setType("HTTP");
         gateway.setExtClass("com.sanerzone.smscenter.gateway.http.handler.impl.SmsApiJYCSMS");
         gateway.setExtParam("{\"apiUrl\":\"http://smsapi.konsone.com:8808/api\",\"userid\":\"3868--\",\"apikey\":\"dac446aa2abf4f30bc6d6bc53abd432d\"}");
         gateway.setReportGetFlag(1);*/
        boolean initResult = false;
        if (GATEWAY_MAP.containsKey(gateway.getGwCode())) {
            return true;
        }
        if (logger.isInfoEnabled()) {
            logger.info("初始化网关:[" + gateway + "]\r\n" + "params:" + gateway.toString());
        }
        if (StringUtils.isBlank(gateway.getGwProto())) {
            return false;
        } else if (GateEnum.HTTP.getValue().equalsIgnoreCase(gateway.getGwProto())) {
             return HTTPGatewayInit(gateway,1, 1);
        } else {
            return  umsGatewayInit(gateway);
        }
    }

    public static boolean updateGW(SmsGateway gateway, int reportStatus, int deliverStatus) {
        if (logger.isInfoEnabled()) {
            logger.info("初始化网关:[" + gateway + "]\r\n" + "params:" + gateway.toString());
        }
        boolean res = false;
        if (StringUtils.isBlank(gateway.getGwProto())) {
            return false;
        } else if (GateEnum.HTTP.getValue().equalsIgnoreCase(gateway.getGwProto())) {
            res =HTTPGatewayInit(gateway, reportStatus, deliverStatus);
        } else {
            res  =umsGatewayInit(gateway);
        }
        if (res) {
            GatewayCacheHelper.put(gateway.getGwCode(), gateway);
        }
        return res;
    }

    @Override
    public void closeAll() {
        Iterator<String> gatewayIt = GATEWAY_MAP.keySet().iterator();
        while (gatewayIt.hasNext()) {
            closeGateway(gatewayIt.next());
        }
    }

    @Override
    public boolean closeGateway(String gwCode) {
        //修改网关状态
        SmsGateway smsGateway = new SmsGateway();
        smsGateway.setGwCode(gwCode);
        smsGateway.setGwStatus(GateStateEnum.DISABLED.getValue());
        smsGatewayService.updateStatus(smsGateway);

        //关闭队列
//    	GateWay smsGateway = getSmsGateWay(id);
//    	if( smsGateway != null) smsGateway.shutdown();

        GATEWAY_MAP.remove(gwCode);
        return true;
    }

    @Override
    public boolean closeGatewayTemp(String id) {
        return closeGateway(id);
    }

    @Override
    public boolean openGateway(String gwCode) {
        Object gate = GATEWAY_MAP.get(gwCode);
        if (gate != null) {
            return true;
        }
        SmsGateway smsGateway = smsGatewayService.findByGwCode(gwCode);
        if (smsGateway == null) {
            return false;
        }
        try {
            boolean res = initGate(smsGateway);
            if (res) {
                smsGateway.setGwStatus(GateStateEnum.ENABLED.getValue());
            } else {
                smsGateway.setGwStatus(GateStateEnum.ERROR.getValue());
            }
            smsGatewayService.updateStatus(smsGateway);
            return res;
        } catch (Exception e) {
            smsGateway.setGwStatus(GateStateEnum.ERROR.getValue());
            smsGatewayService.updateStatus(smsGateway);
            logger.error("初始化网关失败", e);
        }
        return false;
    }

    @Override
    public boolean hasGateway(String gwCode) {
        return GATEWAY_MAP.get(gwCode) != null;
    }

    @Override
    public Object getGateway(String gwCode) {
        logger.info("{}通道 ", gwCode);
        if (!GATEWAY_MAP.containsKey(gwCode)) {
            try {
                SmsGateway smsGateway = smsGatewayService.findByGwCode(gwCode);

                if (!initGate(smsGateway)) {
                    return null;

                }
            } catch (Exception e) {
                return null;
            }
        }
        return (GateWayHttpAbstract) GATEWAY_MAP.get(gwCode);
    }

    @Override
    public Result sendMsg(SMSMTMessage msg) {
        GateWayHttpAbstract gateWay = (GateWayHttpAbstract) this.getGateway(msg.getGatewayId());
        Object gate = GATEWAY_TYPE.get(msg.getGatewayId());
        if (gateWay == null && gate == null) {
            logger.error("{}通道, 未启动", msg.getGatewayId());
//            return new Result("F10104", String.format("%s通道, 未启动", msg.getGatewayId()));
            return new Result("Q000", String.format("%s通道, 未启动", msg.getGatewayId()));
        } else {
            SmsGateway smsGateway = GatewayCacheHelper.get(msg.getGatewayId());
            String code = msg.getGatewayId();
           /* RateLimiter rateLimiter=GatewayCacheHelper.getRateLimitByCode( code );
            rateLimiter.acquire();*/
            try {
                if (StringUtils.equals(smsGateway.getGwProto(), "CMPP20")) {
                    int tempType = fmt_cmpp;
                    CMPPSMProxy proxy = (CMPPSMProxy) gate;
                    if (msg.getPhone().contains(",")) {
                        return new Result("Q000", String.format("%s发送号码有多个", msg.getGatewayId()));
                    } else {
                        logger.info("cmpp提交手机号码：{}", msg.getPhone());
                        Result result = CMPP20Send(proxy, smsGateway, msg, tempType, msg.getPhone());
                        return result;
                    }
                } else if (StringUtils.equals(smsGateway.getGwProto(), "CMPP30")) {

                } else if (StringUtils.equals(smsGateway.getGwProto(), "SGIP")) {
                    int tempType = fmt_sgip;
                    //            int orgType = getInt(message.getContentType());
                    //            if (orgType == 4 || orgType == 21) {
                    //                tempType = orgType;
                    //            }

                    SGIPSMProxy proxy = (SGIPSMProxy) gate;
                    List<SGIPSubmitMessage> list = sgipMsgFactory.buildSGIPSubmitMessage(
                            msg.getSpnumber(), msg.getPhone().split(","), msg.getSmsContent(), tempType, 0,
                            null, 3, String.valueOf(proxy.getCorpId()));
                    Iterator<SGIPSubmitMessage> it = list.iterator();
                    int result = -1;
                    while (it.hasNext()) {
                        SGIPSubmitMessage m = it.next();
                        if (!proxy.isClosed()) {
                            if (logger.isInfoEnabled()) {
                                logger.info("发送消息:" + m);
                            }
                            SGIPSubmitRepMessage res = (SGIPSubmitRepMessage) proxy.send(m);
                            if (logger.isInfoEnabled()) {
                                logger.info("返回消息:" + m + ",返回：" + res + "手机号码：" + msg.getPhone());
                            }
                            if (res == null) {
                                return new Result("T100", "成功");
                            }
                            result = res.getResult();
                            if (result != 0) {
                                break;
                            }
                            getStoredMap().put(res.getSubmitSequenceNumberStr(), msg);
                        } else {
                            try {
                                Thread.sleep(3000L);
                            } catch (InterruptedException e) {
                                logger.error("联通网关断开睡眠", e);
                            }
                        }
                    }
                } else if (StringUtils.equals(smsGateway.getGwProto(), "SMGP3")) {
                    int tempType = fmt_smgp3;
//            int orgType = getInt(message.getContentType());
//            if (orgType == 4 || orgType == 21) {
//                //电信不支持21编码
//                tempType = 4;
//            }
                    List<SMGP3SubmitMessage> list = smgp3MsgFactory.buildSMGP3SubmitMessage(
                            msg.getSpnumber(), msg.getPhone().split(","), msg.getSmsContent(), tempType,
                            null, null, 3, 1);
                    SMGP3SMProxy proxy = (SMGP3SMProxy) gate;
                    Iterator<SMGP3SubmitMessage> it = list.iterator();
                    int result = -1;
                    while (it.hasNext()) {
                        SMGP3SubmitMessage m = it.next();
                        if (!proxy.isClosed()) {
                            if (logger.isInfoEnabled()) {
                                logger.info("发送消息2:" + m);
                            }
                            SMGP3SubmitRespMessage res = (SMGP3SubmitRespMessage) proxy.send(m);
                            if (logger.isInfoEnabled()) {
                                logger.info("返回消息:" + m + ",返回：" + res);
                            }
                            if (res == null) {
                                return new Result("F10105", String.format("send error", msg.getGatewayId()));
                            }
                            result = res.getStatus();
                            SMSSRMessage smsSrMessage = new SMSSRMessage(res.getMsgIdStr(), String.valueOf(result), msg);
                            gateWayMessage.sendSmsSRMessage(smsSrMessage, proxy.getId());
                            if (result != 0) {
                                break;
                            }
                            getStoredMap().put(res.getMsgIdStr(), msg);
                        } else {
                            try {
                                Thread.sleep(3000L);
                            } catch (InterruptedException e) {
                                logger.error("电信网关断开睡眠", e);
                            }
                        }
                    }
                    return new Result("T100", "成功");
                } else if (StringUtils.equals(smsGateway.getGwProto(), "SMGP")) {
                    int tempType = fmt_smgp;
//            int orgType = getInt(message.getContentType());
//            if (orgType == 4 || orgType == 21) {
//                //电信不支持21编码
//                tempType = 4;
//            }
                    List<SMGPSubmitMessage> list = smgpMsgFactory.buildSMGPSubmitMessage(
                            msg.getSpnumber(), msg.getPhone().split(","), msg.getSmsContent(), tempType,
                            null, null, 3, 1);
                    SMGPSMProxy proxy = (SMGPSMProxy) gate;
                    Iterator<SMGPSubmitMessage> it = list.iterator();
                    int result = -1;
                    while (it.hasNext()) {
                        SMGPSubmitMessage m = it.next();
                        if (!proxy.isClosed()) {
                            SMGPSubmitRespMessage res = (SMGPSubmitRespMessage) proxy.send(m);
                            if (logger.isInfoEnabled()) {
                                logger.info("发送消息1:" + m + ",返回：" + res);
                            }
                            if (res == null) {
                                return new Result("F10105", String.format("send error", msg.getGatewayId()));
                            }
                            result = res.getStatus();
                            if (result != 0) {
                                break;
                            }
                            getStoredMap().put(res.getMsgIdStr().toLowerCase(), msg);
                        }
                    }
                    return new Result("T100", "成功");
                } else if (StringUtils.equals(smsGateway.getGwProto(), "HTTP")) {
                    SMSMTMessage e = (SMSMTMessage) gateWayMessage.convertMTMessage(msg, gateWay.isGatewaySign());
                    RateLimiter rateLimiter = GatewayCacheHelper.getRateLimitByCode(code);
                    rateLimiter.acquire();
                    boolean sendFlg = gateWay.send(e);
                    if (sendFlg) {
                        return new Result("T100", "成功");
                    } else {
                        return new Result("F10105", String.format("send error", msg.getGatewayId()));
                    }
                } else {
                    return new Result("F10106", String.format("send GwProto error", msg.getGatewayId()));
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return new Result("F10107", String.format("发送未知UnsupportedEncodingException错误", msg.getGatewayId()));
            } catch (IOException e) {
                e.printStackTrace();
                return new Result("F10108", String.format("发送未知，IO异常", msg.getGatewayId()));
            }
        }
        return new Result("T100", "成功");
    }

    public void sendSmsSRMessage(Serializable message, String gateWayID) {
        gateWayMessage.sendSmsSRMessage(message, gateWayID);
    }

    @Override
    public GateEnum getGatewayType(String gatewayId) {
        return GateEnum.HTTP;
    }

    @Override
    public SMSMTMessage getSubmitResult(String gID, String msgid) {
        return null;
    }


    private static String getStr(Object obj) {
        if (obj == null) {
            return null;
        }
        String str = obj.toString();
        if (org.springframework.util.StringUtils.hasText(str)) {
            return str;
        }
        return null;
    }

    private static String getBoolean(Integer obj) {
        if (obj == null) {
            return "false";
        }
        if (obj == 1) {
            return "true";
        }

        return "false";
    }

    public Result CMPP20Send(CMPPSMProxy proxy, SmsGateway smsGateway, SMSMTMessage msg, int tempType, String phone) {
        List<CMPPSubmitMessage> list;
        try {
            list = cmppMsgFactory.buildCMPPSubmitMessage(smsGateway.getGwServiceId(),
                    smsGateway.getGwSpNumber(), phone.split(","), msg.getSmsContent(), tempType,
                    null, null, 3, 1);
            int result = -1;
            Iterator<CMPPSubmitMessage> it = list.iterator();
            while (it.hasNext()) {
                CMPPSubmitMessage m = it.next();
                if (!proxy.isClosed()) {
                    if (logger.isInfoEnabled()) {
                        logger.info("发送消息:" + m);
                    }
                    CMPPSubmitRepMessage res = (CMPPSubmitRepMessage) proxy.send(m);
                    if (logger.isInfoEnabled()) {
                        logger.info("返回消息:" + m + ",返回：" + res + "手机号码：" + msg.getPhone());
                    }
                    if (res == null) {
                        return new Result("F14001", "返回对象为空");
                    }
                    result = res.getResult();
                    if (result != 0) {
                        break;
                    }
                    getStoredMap().put(res.getMsgIdStr(), msg);
                } else {
                    try {
                        Thread.sleep(3000L);
                    } catch (InterruptedException e) {
                        logger.error("联通网关断开睡眠", e);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("F2100", "CMPP发送失败");
        }
        return new Result("T100", "成功");
    }

    public static boolean HTTPGatewayInit(SmsGateway gateway,int reportStatus, int deliverStatus) {
        String gateWayID = gateway.getGwCode();
        String className = gateway.getGwProtoClass();
        try {
            Class clazz = Class.forName(className);
            Constructor<GateWayHttpAbstract> constructor = clazz.getConstructor(String.class, String.class);
            GateWayHttpAbstract gatewayImpl = constructor.newInstance(gateWayID, gateway.getGwProtoExtparam());
            GATEWAY_MAP.put(gateWayID, gatewayImpl);
            if (gateway.getGwStatus() == 1) {
                int reportSecTime = 0;
                if (reportStatus == 1) {
                    //状态获取方式 0：异步通知 1：主动查询
                    if (StringHelper.equals(gateway.getGwReceiveModel(), "1")) {
                        String jsonParams = Encodes.unescapeHtml(gateway.getGwProtoExtparam());
                        Map<String, Object> paraMap = JSON.parseObject(jsonParams);
                        if (null != paraMap.get("reportSecTime") && StringUtils.isNotBlank(paraMap.get("reportSecTime").toString())) {
                            reportSecTime = Integer.parseInt(paraMap.get("reportSecTime").toString());
                        } else {
                            reportSecTime = 5;
                        }
                    }
                }
                int deliverSecTime = 0;
                if (deliverStatus == 1) {
                    if (gateway.getGwDeliverStatus() == 1) {
                        String jsonParams = Encodes.unescapeHtml(gateway.getGwProtoExtparam());
                        Map<String, Object> paraMap = JSON.parseObject(jsonParams);
                        if (null != paraMap.get("deliverSecTime") && StringUtils.isNotBlank(paraMap.get("deliverSecTime").toString())) {
                            deliverSecTime = Integer.parseInt(paraMap.get("deliverSecTime").toString());
                        } else {
                            deliverSecTime = 30;
                        }
                    }
                }
                gatewayImpl.startListener(reportSecTime, deliverSecTime, gateWayID);
            }
            return true;
        } catch (Exception e) {
            logger.error("初始化网关" + gateway.getId() + "失败", e);
            return false;
        }
    }

    public static boolean umsGatewayInit(SmsGateway gateway) {
        if (gateway.getGwStatus() == 1) {
            Map<String, String> params = new HashMap<String, String>();
            params.put("host", org.springframework.util.StringUtils.trimAllWhitespace(gateway.getGwServerIp()));
            params.put("port", getStr(gateway.getGwServerPort()));
            params.put("local-host", getStr(gateway.getGwLocalIp()));
            params.put("local-port", getStr(gateway.getGwLocalPort()));
            //物理连接读操作超时时间(单位：秒)
            params.put("read-timeout", getStr(gateway.getReadTimeout()));
            //连接中断时重连间隔时间(单位：秒)
            params.put("reconnect-interval", getStr(gateway.getReconnectInterval()));
            //操作超时时间(单位：秒)
            params.put("transaction-timeout", getStr(gateway.getTransactionTimeout()));
            //心跳信息发送间隔时间(单位：秒)
            params.put("heartbeat-interval", getStr(gateway.getHeartbeatInterval()));
            //需要重连时，连续发出心跳而没有接收到响应的个数（单位：个)
            params.put("heartbeat-noresponseout", getStr(gateway.getHeartbeatNoresponseout()));
            //SP…ID(最大为六位字符)
            params.put("source-addr", org.springframework.util.StringUtils.trimAllWhitespace(gateway.getGwUsername()));
            //登录密码
            params.put("shared-secret", org.springframework.util.StringUtils.trimAllWhitespace(gateway.getGwPassword()));
            //双方协商的版本号(大于0，小于256)
            params.put("version", org.springframework.util.StringUtils.trimAllWhitespace(gateway.getGwProtoVersion()));
            params.put("spNumber", org.springframework.util.StringUtils.trimAllWhitespace(gateway.getGwSpNumber()));
            //是否属于调试状态,true表示属于调试状态，所有的消息被打印输出到屏幕，false表示不属于调试状态，所有的消息不被输出
            params.put("debug", getBoolean(1));
            params.put("corpId", org.springframework.util.StringUtils.trimAllWhitespace(gateway.getGwCorpId()));
            params.put("msg_Src", org.springframework.util.StringUtils.trimAllWhitespace(gateway.getGwCorpId()));
            if (logger.isInfoEnabled()) {
                logger.info("初始化网关:[" + gateway + "]\r\n" + "params:" + JSON.toJSONString(params));
            }
            boolean res = false;
            if (GateEnum.CMPP.getValue().equalsIgnoreCase(gateway.getGwProto())) {
                CMPPSMProxy proxy = new CMPPSMProxy(gateway.getGwCode(), params);
                proxy.setMoListener(moListener);
                GATEWAY_TYPE.put(gateway.getGwCode(), proxy);
                res = true;
            } else if (GateEnum.CMPP30.getValue().equalsIgnoreCase(gateway.getGwProto())) {
                CMPP30SMProxy proxy = new CMPP30SMProxy(gateway.getGwCode(), params);
                proxy.setMoListener(moListener);
                GATEWAY_TYPE.put(gateway.getGwCode(), proxy);
                res = true;
            } else if (GateEnum.SGIP.getValue().equalsIgnoreCase(gateway.getGwProto())) {
                params.remove("local-host");
                params.remove("local-port");
                params.put("serviceType", sgipMsgFactory.getServiceType());
                params.put("feeType", getStr(sgipMsgFactory.getFeeType()));
                params.put("feeValue", sgipMsgFactory.getFeeValue());
                params.put("givenValue", sgipMsgFactory.getGivenValue());
                params.put("morelatetoMTFlag", getStr(sgipMsgFactory.getMorelatetoMTFlag()));
                SGIPSMProxy proxy = new SGIPSMProxy(gateway.getGwCode(), params);
                boolean result = proxy.connect(params.get("source-addr"), params.get("shared-secret"));
                if (result) {
                    proxy.startService(getStr(gateway.getGwLocalIp()),
                            Integer.parseInt(getStr(gateway.getGwLocalPort())));
                    proxy.setMoListener(moListener);
                    GATEWAY_TYPE.put(gateway.getGwCode(), proxy);
                    res = true;
                } else {
                    proxy.close();
                }
            } else if (GateEnum.SMGP.getValue().equalsIgnoreCase(gateway.getGwProto())) {
                SMGPSMProxy proxy = new SMGPSMProxy(gateway.getGwCode(), params);
                proxy.setMoListener(moListener);
                GATEWAY_TYPE.put(gateway.getGwCode(), proxy);
                res = true;
            } else if (GateEnum.SMGP3.getValue().equalsIgnoreCase(gateway.getGwProto())) {
                SMGP3SMProxy proxy = new SMGP3SMProxy(gateway.getGwCode(), params);
                proxy.setMoListener(moListener);
                GATEWAY_TYPE.put(gateway.getGwCode(), proxy);
                res = true;
            } else {
                logger.error("初始化网关失败，未知网关类型:[" + gateway + "]");
                res = false;
            }
            return res;
        } else {
            logger.info("初始化时网关处于关闭状态,网关:{},网关名称：{}", gateway.getGwCode(), gateway.getGwName());
            return  false;
        }
    }
}
